package com.github.cyf.config;

import com.github.cyf.interceptor.encrypt.EncryptResultFieldInterceptor;
import com.github.cyf.interceptor.encrypt.IEncryptResultFieldStrategy;
import com.github.cyf.interceptor.log.SqlLogInterceptor;
import com.github.cyf.interceptor.page.PageInterceptor;
import com.github.cyf.interceptor.page.dialect.impl.MySqlDialect;
import com.github.cyf.interceptor.tenant.TenantInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

/**
 * @author chenyifan
 * @create 2024-04-11 9:50
 */
@Configuration
public class InterceptorConfig {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private List<IEncryptResultFieldStrategy> encryptStrategies;

    @PostConstruct
    public void addInterceptor() {
        org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
        configuration.addInterceptor(encryptResultFieldInterceptor(encryptStrategies));
        configuration.addInterceptor(sqlLogInterceptor());
        configuration.addInterceptor(tenantInterceptor());
        configuration.addInterceptor(pageInterceptor());
    }

    public SqlLogInterceptor sqlLogInterceptor() {
        SqlLogInterceptor interceptor = new SqlLogInterceptor();
        Properties properties = new Properties();
        properties.setProperty(SqlLogInterceptor.IS_PRINT_SQL_TIME, Boolean.TRUE.toString());
        interceptor.setProperties(properties);
        return interceptor;
    }

    public PageInterceptor pageInterceptor() {
        PageInterceptor interceptor = new PageInterceptor();
        interceptor.setDialect(new MySqlDialect());
        return interceptor;
    }

    public EncryptResultFieldInterceptor encryptResultFieldInterceptor(List<IEncryptResultFieldStrategy> encryptStrategies) {
        return new EncryptResultFieldInterceptor(encryptStrategies);
    }

    public TenantInterceptor tenantInterceptor() {
        TenantInterceptor interceptor = new TenantInterceptor();
        interceptor.setTenantIdColumn("tenant_id");
        return interceptor;
    }

}
